package com.oceanread.cn.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.oceanread.cn.config.MyConfig;
import com.oceanread.cn.config.Result;
import com.oceanread.cn.entity.Drillhole1;
import com.oceanread.cn.entity.Drillhole2;
import com.oceanread.cn.entity.Query;
import com.oceanread.cn.service.IDrillhole1Service;
import com.oceanread.cn.service.IDrillhole2Service;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;


@RestController
@RequestMapping("/Drillhole1")
@CrossOrigin()
@Api(value = "", tags = {"2.1.1-钻孔信息"})
public class Drillhole1Controller {
    @Autowired
    private IDrillhole1Service iDrillhole1Service;
    @Autowired
    private IDrillhole2Service iDrillhole2Service;

    @ApiIgnore
    @GetMapping("/getall")
    public List<Drillhole1> getAll() {
        return iDrillhole1Service.getall();
    }

    @ApiOperation(value = "获取项目信息")
    @GetMapping("/getPrj")
    public JSONObject getPrj(@RequestParam(name = "prjCode", required = true, defaultValue = "DTNA") String prjCode,
                             @RequestParam(name = "page", required = true, defaultValue = "1") int page,
                             @RequestParam(name = "size", required = true, defaultValue = "10") int size) {
        JSONObject object = new JSONObject();
        object.put("data", iDrillhole1Service.getPrj(prjCode, page, size));
        object.put("total", iDrillhole1Service.getPrjnum(prjCode));
        return object;
    }

    @ApiOperation(value = "获取钻孔图片")
    @RequestMapping(value = "/getPhoto/{prjCode}/{imgUrl}", produces = MediaType.IMAGE_JPEG_VALUE, method = RequestMethod.GET)
    @ResponseBody
    public byte[] getPhoto(@PathVariable("prjCode") String prjCode, @PathVariable("imgUrl") String imgUrl) {
        try {
            System.out.println(prjCode);
            System.out.println(imgUrl);
            File file = new File(MyConfig.getFilepath() + "image/Drillhole/" + prjCode + "/" + imgUrl);
            System.out.println(file.getPath());
            FileInputStream inputStream = new FileInputStream(file);
            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes, 0, inputStream.available());
            return bytes;
        } catch (Exception e) {
            return null;
        }
    }

    @ApiOperation(value = "上传钻孔图片")
    @RequestMapping(value = "/uploadPhoto/{prjCode}", method = RequestMethod.POST)
    @ResponseBody
    public Result uploadPhoto(@PathVariable("prjCode") String prjCode, @RequestParam("file") MultipartFile file) {
        String fileName = file.getOriginalFilename();
        //设置文件上传路径
        String filePath = MyConfig.getFilepath() + "image/Drillhole/" + prjCode + "/";
        System.out.println(filePath);
        try {
            uploadFile(file.getBytes(), filePath, fileName);
            return Result.success();
        } catch (Exception e) {
            return Result.error();
        }
    }

    public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
        /*前端上传图片后，保存到本地*/
        File path = new File(filePath);
        if (!path.exists() && !path.isDirectory()) {
            try {
                path.mkdir();
                System.out.println("//已创建新项目文件夹");
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
        System.out.println(filePath + fileName);
        FileOutputStream out = new FileOutputStream(filePath + fileName);
        out.write(file);
        out.flush();
        out.close();
    }

    @ApiOperation(value = "更新Drillhole1")
    @PostMapping("/update")
    public Integer update(@RequestBody Drillhole1 drillhole1) {
        return iDrillhole1Service.update(drillhole1);
    }

    @ApiIgnore
    @PostMapping("/insert")
    public Integer insert1(@RequestBody Drillhole1 drillhole1) {
        return iDrillhole1Service.insert(drillhole1.getPrjCode(), drillhole1.getCode(), drillhole1.getName(),
                drillhole1.getPrjID(), drillhole1.getType(), drillhole1.getEquipment(), drillhole1.getLat(),drillhole1.getLon(),
                drillhole1.getEast(),  drillhole1.getNorth(), drillhole1.getSampling(),
                drillhole1.getResponsible(), drillhole1.getDrawing(), drillhole1.getProofreading(), drillhole1.getCatalog(),
                drillhole1.getTime(), drillhole1.getDiameter(), drillhole1.getAltitude(), drillhole1.getStart(),
                drillhole1.getThickness(), drillhole1.getMaterial(), drillhole1.getMaterial0());
    }
@ApiOperation(value = "删除Drillhole1")
    @GetMapping("/delete")
    public Integer delete1(@RequestParam(name = "SYSID") int SYSID) {
        return iDrillhole1Service.delete(SYSID);
    }

    @ApiOperation(value = "模糊查询Drillhole1")
    @GetMapping("/query1")
    public JSONObject query1(@RequestParam(name = "page", required = true, defaultValue = "1") int page,
                             @RequestParam(name = "size", required = true, defaultValue = "10") int size,
                             @RequestParam(name = "key") String key,
                             @RequestParam(name = "value") String value
    ) {
        JSONObject object = new JSONObject();
        object.put("data", iDrillhole1Service.query1(key, value, page, size));
        object.put("total", iDrillhole1Service.getnumquery(key, value));
        return object;
    }
    @ApiOperation(value = "需前端可视化接口_获取钻孔信息")
    @GetMapping("/geojson")
    public JSONArray getGeojson(@RequestParam(defaultValue = "PrjCode") String key, @RequestParam(defaultValue ="DTNA" ) String value) {
        Query query = new Query();
        query.setKey(key);
        query.setValue(value);
        System.out.println(key + "   " + value);
        JSONArray jsonArray = new JSONArray();
        List<Drillhole1> list = iDrillhole1Service.query(query.getKey(), query.getValue());
        for (Drillhole1 drillhole1 : list) {
            JSONObject itemObject = (JSONObject) JSONObject.toJSON(drillhole1);
            String material = drillhole1.getMaterial();
            System.out.println(material);
//            System.out.println(material.hashCode());
            if ( material==null||material.equals("") || material.equals("null")) {
                System.out.println(drillhole1.getPrjID());
                Query query2 = new Query();
                query2.setKey("PrjID");
                query2.setValue(drillhole1.getPrjID());
                JSONArray array = new JSONArray();
                List<Drillhole2> listDrillhole2 = iDrillhole2Service.query2json(query.getKey(), query.getValue(), query2.getKey(), query2.getValue());
                for (Drillhole2 drillhole2 : listDrillhole2) {
                    Object jsonObject2 = JSON.toJSON(drillhole2);
                    array.add(jsonObject2);
                }
                itemObject.put("Part", array); // 直接put会修改相同的key
            } else {
                JSONArray jsonArray1 = new JSONArray();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("Altitude", drillhole1.getAltitude());
                jsonObject.put("Start", drillhole1.getStart());
                jsonObject.put("Thickness", drillhole1.getThickness());
                jsonObject.put("Material", drillhole1.getMaterial());
                jsonArray1.add(jsonObject);
                itemObject.put("Part", jsonArray1);
            }
            jsonArray.add(itemObject);
        }

        return jsonArray;
    }

    @ApiOperation(value = "Drillhole12统一插入")
    @RequestMapping(value = "/DrillholeInsert", method = RequestMethod.POST)
    public void inserttest(HttpServletRequest request, HttpServletResponse response) {
        try {
            BufferedReader reader = request.getReader();
            if (reader != null) {
                String redaline = reader.readLine();
                JSONObject readobject = JSONObject.parseObject(redaline);
                JSONObject data = readobject.getJSONObject("data");
                System.out.println(data);
                String PrjCode = data.getString("PrjCode");
                String Name = data.getString("Name");

                String PrjID = data.getString("PrjID");
                String Catalog = data.getString("Catalog");
                String Lon = data.getString("Lon");
                String Lat = data.getString("Lat");
                String Sampling = data.getString("Sampling");
                String Responsible = data.getString("Responsible");
                String Drawing = data.getString("Drawing");
                String Proofreading = data.getString("Proofreading");
                Drillhole1 drillhole1 = new Drillhole1();
                drillhole1.setPrjCode(PrjCode);
                drillhole1.setName(Name);
                drillhole1.setPrjID(PrjID);
                drillhole1.setCatalog(Catalog);
                drillhole1.setLon(Lon);
                drillhole1.setLat(Lat);
                drillhole1.setSampling(Sampling);
                drillhole1.setResponsible(Responsible);
                drillhole1.setDrawing(Drawing);
                drillhole1.setProofreading(Proofreading);
                JSONArray material = data.getJSONArray("material");
                ArrayList<Drillhole2> drillhole2List = new ArrayList<Drillhole2>();
                if (material.size() == 1) {
                    drillhole1.setMaterial(material.getJSONObject(0).getString("Material"));
                    drillhole1.setStart(material.getJSONObject(0).getString("Start"));
                    drillhole1.setThickness(material.getJSONObject(0).getString("Thickness"));
                    drillhole1.setMaterial0(material.getJSONObject(0).getString("MaterialO"));
                } else if (material.size() > 1) {
                    for (int i = 0; i < material.size(); i++) {
                        Drillhole2 drillhole2 = new Drillhole2();
                        drillhole2.setPrjCode(PrjCode);
                        drillhole2.setPrjID(PrjID);
                        drillhole2.setOrder(Integer.parseInt(material.getJSONObject(i).getString("Order")));
                        drillhole2.setMaterial(material.getJSONObject(i).getString("Material"));
                        drillhole2.setStart(material.getJSONObject(i).getString("Start"));
                        drillhole2.setThickness(material.getJSONObject(i).getString("Thickness"));
                        drillhole2.setMaterial0(material.getJSONObject(i).getString("MaterialO"));
                        drillhole2List.add(drillhole2);
                    }
                }
                if (drillhole1.getPrjID()!=""){
                    iDrillhole1Service.insert(drillhole1.getPrjCode(), drillhole1.getCode(), drillhole1.getName(),
                            drillhole1.getPrjID(), drillhole1.getType(), drillhole1.getEquipment(), drillhole1.getLat(),drillhole1.getLon(),
                            drillhole1.getEast(), drillhole1.getNorth(), drillhole1.getSampling(),
                            drillhole1.getResponsible(), drillhole1.getDrawing(), drillhole1.getProofreading(), drillhole1.getCatalog(),
                            drillhole1.getTime(), drillhole1.getDiameter(), drillhole1.getAltitude(), drillhole1.getStart(),
                            drillhole1.getThickness(), drillhole1.getMaterial(), drillhole1.getMaterial0());
                    for (Drillhole2 drillhole2 : drillhole2List) {//循环插入材质
                        iDrillhole2Service.insert(
                                drillhole2.getPrjCode(), drillhole2.getPrjID(), drillhole2.getOrder(),
                                drillhole2.getAltitude(), drillhole2.getStart(), drillhole2.getThickness(),
                                drillhole2.getMaterial(), drillhole2.getMaterial0());
                    }
                }
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        System.out.println();

    }
}
